/*
 * ServerConnection.cpp
 *
 *  Created on: 15 mei 2013
 *      Author: maarten
 */

#include "ServerConnection.hpp"
#include "Logger.hpp"
#include "Config.hpp"

ServerConnection::ServerConnection() {
	int port = Config::getInstance().getPort();
	int nrOfCon = Config::getInstance().getNrOfClients();
	serverSocket = 0;

	std::memset(&server, 0, sizeof(server)); 		//set struct to zero
	server.sin_family = PF_INET; 					//Use IPv4
	server.sin_addr.s_addr = htonl(INADDR_ANY ); 	//Listen to any IP
	server.sin_port = htons(port); 					//Set the listen port

	//create socket with IPv4 and TCP
	if ((serverSocket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		perror("Can't socket");
		exit(-1);
	}

	//bind socket
	if (bind(serverSocket, (struct sockaddr *) &server, sizeof(server)) == -1) {
		perror("Can't bind");
		exit(-1);
	}

	//listen to incoming messages
	if (listen(serverSocket, nrOfCon) == -1) {
		perror("Can't listen");
		exit(-1);
	}
}

ServerConnection::~ServerConnection() {
}

ClientConnection ServerConnection::waitForClient() {
	struct sockaddr connectie;
	socklen_t conlen = sizeof(connectie);
	int socket = accept(serverSocket, &connectie, &conlen);

	return ClientConnection(socket, connectie);
}
